import { CacheTagView, TagView, IframeContent, TagViewContentType } from "@/framework/tag-view";
import { Module, VuexModule, Action } from "vuex-class-modules";
import { AsciiCode } from "@/framework/crypto";

function setCacheVisitedViews(views: TagView[]) {
  sessionStorage.setItem("CACHE:VISITEDVIEWS", JSON.stringify(views));
}
function getCacheVisitedViews(): TagView[] {
  const viewStr = sessionStorage.getItem("CACHE:VISITEDVIEWS");
  if (viewStr) {
    return JSON.parse(viewStr);
  }
  return [];
}
function setCurrentView(view: TagView) {
  sessionStorage.setItem("CACHE:CURRENTVIEW", JSON.stringify(view));
}
function getCurrentView(): TagView {
  const viewStr = sessionStorage.getItem("CACHE:CURRENTVIEW");
  if (viewStr) {
    return JSON.parse(viewStr);
  }
  return null;
}
function setCacheSortTabsUUID(uuids) {
  sessionStorage.setItem("CACHE:SORTTABSUUID", JSON.stringify(uuids));
}
function getCacheSortTabsUUID(): string[] {
  const tabsUUID = sessionStorage.getItem("CACHE:SORTTABSUUID");
  if (tabsUUID) {
    return JSON.parse(tabsUUID);
  }
  return [];
}

@Module({ generateMutationSetters: true })
export default class TagsViewStore extends VuexModule {
  /** 用于排序的 UUID */
  sortVisitedViewsUUID = getCacheSortTabsUUID();
  /** 显示的页面视图 */
  visitedViews: TagView[] = getCacheVisitedViews();
  /** 已缓存的视图的名称 */
  cachedViews: CacheTagView[] = [];
  /** 当前显示的视图 */
  currentView: TagView = getCurrentView();
  /** iframe-content 的缓存 */
  iframeCachedViews: IframeContent[] = [];

  get keepAliveViews() {
    return this.cachedViews
      .filter(f => !f.isExpire)
      .map(m => m.componentName)
      .filter(f => f);
  }
  get hasVisitedViews() {
    return Boolean(this.visitedViews.length);
  }
  get sortVisitedViews(): TagView[] {
    console.log("done");

    return this.sortVisitedViewsUUID.map(uuid => this.visitedViews.find(f => f.uuid === uuid));

    // // 优先将固定的tab 放入进去
    // const fixedViews = this.visitedViews.filter(f => f.isFixed).sort((a, b) => asc(a.order, b.order));
    // // 将其他标签卡放进去
    // const unFixedViews = this.visitedViews.filter(f => !f.isFixed).sort((a, b) => asc(a.order, b.order));
    // console.log(fixedViews, unFixedViews);
    // return [...fixedViews, ...unFixedViews];
  }

  @Action
  async updateSortVisitedViewsUUID(uuids) {
    this.sortVisitedViewsUUID = uuids;
    setCacheSortTabsUUID(uuids);
  }

  @Action
  async isVisitedView(viewUrl) {
    return this.visitedViews.some(f => f.realUrl === viewUrl || f.url === viewUrl);
  }

  @Action
  async tryAddView(view: TagView) {
    // 查找传入的地址在显示的页面中是否存在，依据真实地址 + 访问地址来检测
    const visitedView = this.visitedViews.find(f => f.realUrl === view.url || f.url === view.url);
    if (visitedView) {
      return visitedView;
    }
    if (view.type === TagViewContentType.VueInstance) {
      const url = new URL(view.url, location.origin);
      url.pathname = url.pathname.toLocaleLowerCase();
      // 如果没找到相关的页面，则真实地址还需要进行生成
      view.realUrl = "/general-" + AsciiCode(url.pathname + url.search + url.hash);
    } else {
      view.realUrl = view.url;
    }

    // view.order = (max(this.visitedViews.map(m => m.order)) || 0) + 1;
    // 增加显示的标签
    this.visitedViews.push(view);
    setCacheVisitedViews(this.visitedViews);
    this.sortVisitedViewsUUID.push(view.uuid);
    setCacheSortTabsUUID(this.sortVisitedViewsUUID);

    return view;
  }
  @Action
  async activeView({ path, componentName }) {
    // 激活视图
    const view = this.visitedViews.find(s => s.realUrl === path);
    // 判断视图是否在显示视图列表中，并且非当前页面
    if (view) {
      view.componentName = componentName;
      this.currentView = view;
      setCurrentView(view);
    }
  }

  @Action
  async removeVisitedView(view: TagView) {
    const index = this.sortVisitedViews.findIndex(f => f.uuid === view.uuid);
    if (index >= 0) {
      // 清除数据;
      const view = this.sortVisitedViews[index];
      if (view.type === TagViewContentType.Iframe) {
        const ifmId = AsciiCode(decodeURIComponent(view.url.substring("/iframe/".length)));
        const index = this.iframeCachedViews.findIndex(f => f.id === ifmId);

        if (index >= 0) {
          this.iframeCachedViews.splice(index, 1);
        }
      } else {
        const index = this.cachedViews.findIndex(f => f.componentName === view.componentName);
        if (index >= 0) {
          this.cachedViews.splice(index, 1);
        }
      }
      // 找到这个 tabview 的位置并删除它
      this.visitedViews.splice(this.visitedViews.indexOf(view), 1);
      setCacheVisitedViews(this.visitedViews);
      // view.uuid
      const uuidIndex = this.sortVisitedViewsUUID.findIndex(uuid => uuid === view.uuid);
      if (uuidIndex >= 0) {
        this.sortVisitedViewsUUID.splice(uuidIndex, 1);
        setCacheSortTabsUUID(this.sortVisitedViewsUUID);
      }
    }
    return index;
  }

  @Action
  async addCachedView(componentName) {
    const cachedView = this.cachedViews.find(f => f.componentName === componentName);
    const expireTime = new Date(Date.now() + 1000 * 60 * 20);
    if (cachedView) {
      cachedView.expireTime = expireTime;
    } else {
      this.cachedViews.push(new CacheTagView(componentName, expireTime));
    }
  }

  @Action
  async addIframeCachedView(view: IframeContent) {
    if (!this.iframeCachedViews.some(s => s.id === view.id)) {
      this.iframeCachedViews.push(view);
    }
  }

  @Action
  async removeCachedView(componentName) {
    const index = this.cachedViews.findIndex(f => f.componentName === componentName);
    if (index >= 0) {
      this.cachedViews.splice(index, 1);
    }
  }
}
